package hot_100;

public class 岛屿数量 {


    public static void main(String[] args) {

    }

    int[][] vis = new int[301][301];
    int[][] fang = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    int cnt = 0, n, m;

    public int numIslands(char[][] grid) {
        n = grid.length;
        m = grid[0].length;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '1' && vis[i][j] == 0) {
                    cnt++;
                    dfs(i, j, grid);
                }
            }
        }
        return cnt;
    }

    public void dfs(int x, int y, char[][] grid) {
        vis[x][y] = cnt;
        for (int[] ints : fang) {
            int dx = x + ints[0];
            int dy = y + ints[1];
            if (dx >= 0 && dx < n && dy >= 0 && dy < m && grid[dx][dy] == '1' && vis[dx][dy] == 0) {
                dfs(dx, dy, grid);
            }
        }
    }
}
